<template>
  <div class="tem-table">
    <CHeader :keyword="keyword" @onKeywordChange="onKeywordChange" @onClearKeyword="onClearKeyword" @onSearch="onSearch"
             @onReset="onReset"
             @onNew="showNew=true"/>
    <div class="tem-table-box">
      <el-table v-loading="loading" height="100%" :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="用户ID" min-width="100"/>
        <el-table-column prop="uname" label="用户名" min-width="120"/>
        <el-table-column prop="name" label="姓名" min-width="120"/>
        <el-table-column prop="sexName" label="性别" min-width="80"/>
        <el-table-column prop="jobTitle" label="职称" min-width="150"/>
        <el-table-column prop="mobile" label="手机号" min-width="140"/>
        <el-table-column prop="email" label="邮箱" min-width="160"/>
        <el-table-column label="管理员" min-width="100">
          <template #default="{ row }">
            <el-tag :type="row.roleLevel === RoleLevels.ADMIN ?'success':'info'">
              {{ row.roleLevel === RoleLevels.ADMIN ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="140">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="onSetAdmin(row.id)">
              {{ row.roleLevel === RoleLevels.ADMIN ? '降级为普通用户' : '升级为管理员' }}
            </el-button>
            <el-button link type="danger" size="small" @click="onDel(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="display: flex; justify-content: flex-end; padding: 10px;">
      <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          @size-change="handleSizeChange"
          @current-change="handleNoChange"
      />
    </div>
  </div>

  <el-dialog width="500px" v-model="showNew" title="创建用户">
    <el-form :rules="rules" ref="formRef" :model="submitForm" label-width="100px">
      <el-form-item label="用户名" prop="uname">
        <el-input placeholder="输入用户名" style="width: 100%;" v-model="submitForm.uname"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="passwd">
        <el-input placeholder="输入密码" style="width: 100%;" v-model="submitForm.passwd"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="passwd">
        <el-input placeholder="输入昵称" style="width: 100%;" v-model="submitForm.name"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showNew = false">取 消</el-button>
      <el-button type="primary" @click="newUser(formRef)">提 交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {onMounted} from "vue";
import {
  ElMessage,
  ElMessageBox, FormInstance,
} from 'element-plus';

import CHeader from '@/components/CHeader.vue';
import RoleLevels from '@/config/RoleLevels';
import {
  createVirtualUser,
  delUser,
  getAllUserList,
  setAdmin,
} from '@/service/UserManager';
import {EditAppRoleArgs} from "@/service/AppManager";

onMounted(() => {
  updata()
})

const total = ref(0)
const pageNo = ref(1)
const pageSize = ref(10)
const keyword = ref('')
const tableData = ref([])
const loading = ref(false)
const showNew = ref(false)

const submitForm = reactive({
  uname: '',
  passwd: '',
  name: ''
})
const formRef = ref<FormInstance>()
const rules = reactive({
  uname: [{required: true, message: '用户名必填', trigger: 'blur'}],
  passwd: [{required: true, message: '密码必填', trigger: 'blur'}],
  name: [{required: true, message: '昵称必填', trigger: 'blur'}]
})

const onKeywordChange = (val: string) => {
  keyword.value = val
  updata()
}

const onClearKeyword = () => {
  keyword.value = ''
  updata()
}

const onSearch = async () => {
  updata()
}

const onReset = async () => {
  keyword.value = ''
  pageNo.value = 1
  pageSize.value = 10
  updata()
}

const newUser = async (formRef: FormInstance | undefined) => {
  console.log(formRef)
  if (!formRef) {
    return
  }
  await formRef.validate(async (valid, fields) => {
    if (valid) {
      const res = await createVirtualUser(submitForm.uname, submitForm.passwd, submitForm.name)
      if (!res) return false
      showNew.value = false
      formRef.resetFields()
      updata()
      ElMessage({
        type: 'success',
        message: '创建成功'
      })
      return true
    } else {
      return false
    }
  })
}

const onSetAdmin = async (id: number) => {
  const res = await setAdmin(id)
  if (!res) return
  ElMessage({
    type: 'success',
    message: '设置成功'
  })
  updata()
}

const onDel = (id: number) => {
  ElMessageBox.confirm(
      '永久删除该条信息. 是否确认?',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const res = await delUser(id)
        if (res) {
          updata()
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })

}

async function updata() {
  loading.value = true
  try {
    const res = await getAllUserList({pageNo: pageNo.value, pageSize: pageSize.value, keyword: keyword.value})
    tableData.value = res.arr
    total.value = res.total
  } finally {
    setTimeout(() => loading.value = false, 200)
  }
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  updata()
}
const handleNoChange = (val: number) => {
  pageNo.value = val
  updata()
}

</script>

<style scoped lang="scss">
@import "@/global.scss";

.tem-table {
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: var(--ap-box-shadow-light);
  box-sizing: border-box;
  padding: 10px;
}


.tem-table-box {
  flex: 1;
  overflow: hidden;
}
</style>